package com.jacken.mars.commons.message;

import com.jacken.mars.commons.constant.CommonConstants;
import com.jacken.mars.commons.constant.SmsServiceConstants;
import com.jacken.mars.entity.req.SmsReq;
import com.jacken.mars.commons.enums.SmsTypeEnum;
import com.jacken.mars.commons.exception.WorkException;
import com.jacken.mars.commons.message.config.SmsConfig;
import com.jacken.mars.utils.RandomUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author wq
 * @version 1.0
 * @date 2020/12/15 17:52
 */
@Component
@Slf4j
public class SmsManager {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private ThreadPoolTaskExecutor executorService;

    @Resource
    private AliMessageManager aliMessageManager;

    @Resource
    private SmsConfig smsConfig;

    @Value("${spring.profiles.active}")
    private String env;


    /**
     * 发送短信验证码
     *
     * @param smsReq req
     */
    public boolean sendMessage(SmsReq smsReq) {
        // 验证码的平台
        String messagePlatform = smsReq.getSmsPlatform();
        // 验证码的类型
        String messageType = smsReq.getSmsType();
        // 拼接key
        String key = String.format(SmsServiceConstants.SMS_KEY, messagePlatform, messageType, smsReq.getMobile());
        Boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey != null && hasKey) {
            throw new WorkException("操作频繁,稍后再试");
        }
        if (CommonConstants.DEV.equals(env) || CommonConstants.TEST.equals(env)) {
            String testCode = smsConfig.getTestCode();
            if (org.springframework.util.StringUtils.isEmpty(testCode)) {
                //默认验证码
                testCode = "1111";
            }
            //验证码默认 两分钟
            redisTemplate.opsForValue().set(key, testCode, 60, TimeUnit.SECONDS);
            return true;
        }
        executorService.submit(() -> {
            String code = RandomUtils.randomCode(6);
            log.info("--手机号->{}--短信验证码code >{}", smsReq.getMobile(), code);
            try {
                aliMessageManager.sendSms(smsReq.getSmsPlatform(), smsReq.getMobile(), code, SmsTypeEnum.SMS_168775045.toString());
            } catch (Exception e) {
                log.error("短信发送失败", e.getMessage());
                e.printStackTrace();
            }
            redisTemplate.opsForValue().set(key, code, 60, TimeUnit.SECONDS);
        });
        return true;
    }


    /**
     * 校验短信验证码
     *
     * @param smsRequest req
     */
    public boolean checkSmsCode(SmsReq smsRequest) {
        if (Objects.isNull(smsRequest)) {
            throw new WorkException("请输入验证码");
        }
        // 验证码的平台
        String messagePlatform = smsRequest.getSmsPlatform();
        // 验证码的类型
        String messageType = smsRequest.getSmsType();
        // 拼接key
        String key = String.format(SmsServiceConstants.SMS_KEY, messagePlatform, messageType, smsRequest.getMobile());
        Object result = redisTemplate.opsForValue().get(key);
        if (null == result) {
            throw new WorkException("请先获取验证码");
        } else {
            if (StringUtils.isNotEmpty(result.toString()) && smsRequest.getCode().equals(result.toString())) {
                redisTemplate.delete(key);
                return true;
            } else {
                throw new WorkException("短信验证码失败");
            }
        }
    }

}
